// src/services/aiService.ts
import api from './api';
import {BackendChatHistoryResponse, ChatMessage, Translation, VoiceRecord} from '../types';


interface ChatRequest {
  message: string;
  model: string;
  conversationId?: string;
  temperature?: number;
  maxTokens?: number;
}

interface ChatResponse {
  reply: string;
  conversationId: string;
  usage: {
    tokens: number;
    cost?: number;
  };
}

interface TranslateRequest {
  text: string;
  sourceLang: string;
  targetLang: string;
}

interface TranslateResponse {
  translatedText: string;
  detectedLanguage?: string;
  confidence?: number;
}

interface VoiceToTextRequest {
  audioUrl: string;
  language?: string;
}

interface VoiceToTextResponse {
  text: string;
  confidence: number;
  duration: number;
}

interface UsageStats {
  daily: {
    chatCount: number;
    translationCount: number;
    voiceCount: number;
    totalTokens: number;
  };
  monthly: {
    chatCount: number;
    translationCount: number;
    voiceCount: number;
    totalTokens: number;
    estimatedCost: number;
  };
  limits: {
    dailyChatLimit: number;
    dailyTranslationLimit: number;
    dailyVoiceLimit: number;
  };
}

class AIService {
  // AI聊天
  async chat(request: ChatRequest): Promise<ChatResponse> {
    const response = await api.post<ChatResponse>('/ai/chat', request);
    return response.data;
  }

  // 获取聊天历史
  async getChatHistory(conversationId?: string, page = 1, size = 20): Promise<{
    messages: ChatMessage[];
    total: number;
    hasMore: boolean;
  }> {
    try {
      const response = await api.get<BackendChatHistoryResponse>('/ai/chat/history', {
        params: { conversationId, page, size },
      });

      // 转换后端数据格式为前端期望的格式
      const messages: ChatMessage[] = [];

      response.data.messages.forEach((item, index) => {
        // 添加用户消息
        messages.push({
          id: `user_${item.id || 'default'}_${index}_${Date.now()}`,
          role: 'user',
          content: item.userMessage,
          timestamp: item.createdAt,
          conversationId: item.conversationId || `conv_${Date.now()}`,
          tokensUsed: 0,
        });

        // 添加AI回复
        messages.push({
          id: `assistant_${item.id || 'default'}_${index}_${Date.now()}`,
          role: 'assistant',
          content: item.aiReply,
          timestamp: item.createdAt,
          conversationId: item.conversationId || `conv_${Date.now()}`,
          tokensUsed: item.tokensUsed,
        });
      });

      // 按时间排序（最新的在后面，符合聊天界面习惯）
      messages.sort((a, b) => {
        const timeA = new Date(a.timestamp || 0).getTime();
        const timeB = new Date(b.timestamp || 0).getTime();
        return timeA - timeB;
      });

      return {
        messages,
        total: response.data.total,
        hasMore: response.data.hasMore,
      };
    } catch (error) {
      console.error('Get chat history error:', error);
      throw error;
    }
  }

  // 获取最近聊天记录（用于首页显示）
  async getRecentChatMessages(limit = 3): Promise<ChatMessage[]> {
    try {
      const response = await this.getChatHistory(undefined, 1, limit * 2); // 获取更多数据以确保有足够的用户消息

      // 只返回用户消息用于首页显示
      return response.messages
          .filter(msg => msg.role === 'user')
          .slice(0, limit);
    } catch (error) {
      console.error('Get recent chat messages error:', error);
      throw error;
    }
  }

  // 删除聊天历史
  async deleteChatHistory(conversationId: string): Promise<void> {
    await api.delete(`/ai/chat/history/${conversationId}`);
  }

  // 文本翻译
  async translate(request: TranslateRequest): Promise<TranslateResponse> {
    const response = await api.post<TranslateResponse>('/ai/translate', request);
    return response.data;
  }

  // 批量翻译
  async batchTranslate(texts: string[], sourceLang: string, targetLang: string): Promise<TranslateResponse[]> {
    const response = await api.post<TranslateResponse[]>('/ai/batch-translate', {
      texts,
      sourceLang,
      targetLang,
    });
    return response.data;
  }

  // 获取翻译历史
  async getTranslationHistory(page = 1, size = 20): Promise<{
    translations: Translation[];
    total: number;
    hasMore: boolean;
  }> {
    const response = await api.get('/ai/translate/history', {
      params: { page, size },
    });
    return response.data;
  }

  // 语音转文字
  async voiceToText(request: VoiceToTextRequest): Promise<VoiceToTextResponse> {
    try {
      const response = await api.post<VoiceToTextResponse>('/ai/voice-to-text', request);
      return response.data;
    } catch (error) {
      console.error('Voice to text error:', error);
      throw new Error('语音识别服务暂时不可用');
    }
  }

  // 文字转语音
  async textToVoice(text: string, voice?: string, speed?: number): Promise<string> {
    try {
      const response = await api.post<{ audioUrl: string }>('/ai/text-to-voice', {
        text,
        voice,
        speed,
      });
      return response.data.audioUrl;
    } catch (error) {
      console.error('Text to voice error:', error);
      throw new Error('语音合成服务暂时不可用');
    }
  }

  // 获取语音历史
  async getVoiceHistory(page = 1, size = 20): Promise<{
    records: VoiceRecord[];
    total: number;
    hasMore: boolean;
  }> {
    try {
      const response = await api.get('/ai/voice-to-text-history', {
        params: { page, size },
      });
      return response.data;
    } catch (error) {
      console.error('Get voice history error:', error);
      throw error;
    }
  }

  // 获取使用统计
  async getUsageStats(): Promise<UsageStats> {
    const response = await api.get<UsageStats>('/ai/usage/stats');
    return response.data;
  }

  // 获取支持的语言
  async getSupportedLanguages(): Promise<Array<{
    code: string;
    name: string;
    nativeName: string;
  }>> {
    const response = await api.get('/ai/languages');
    return response.data;
  }

  // 获取AI模型列表
  async getModels(): Promise<Array<{
    id: string;
    name: string;
    description: string;
    maxTokens: number;
    costPerToken: number;
  }>> {
    const response = await api.get('/ai/models');
    return response.data;
  }
}

export default new AIService();